﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Web.Security;

namespace AIC_KQKT
{
    public partial class UCCreateUser : System.Web.UI.UserControl
    {
        private static int ID;
        private string MyAction = MyConst.Action.Addnew;
        private string MyMaDM = "";

        #region Ham Su kien
        protected void Page_Load(object sender, EventArgs e)
        {
            if (CheckPermision())
            {
                formUpdate.Visible = false;
                Config();
                if (!IsPostBack)
                {
                    BindDataToGrid("");
                }
            }
            else
            {
                Response.Redirect("index.php");
            }
        }

        private void Config()
        {
            if (MyMaDM == MyConst.DanhMuc.CapBac.Ma)
                lblFormName.InnerText = "Quản trị danh mục " + MyConst.DanhMuc.CapBac.Ten;
            else if (MyMaDM == MyConst.DanhMuc.Quyen.Ma)
                lblFormName.InnerText = "Quản trị danh mục " + MyConst.DanhMuc.Quyen.Ten;
            else if (MyMaDM == MyConst.DanhMuc.NhomUser.Ma)
                lblFormName.InnerText = "Quản trị danh mục " + MyConst.DanhMuc.NhomUser.Ten;
            else if (MyMaDM == MyConst.DanhMuc.TrinhDo.Ma)
                lblFormName.InnerText = "Quản trị danh mục " + MyConst.DanhMuc.TrinhDo.Ten;
            else if (MyMaDM == MyConst.DanhMuc.ChucVu.Ma)
                lblFormName.InnerText = "Quản trị danh mục " + MyConst.DanhMuc.ChucVu.Ten;
            else if (MyMaDM == MyConst.DanhMuc.BaoCaoDinhKem.Ma)
                lblFormName.InnerText = "Quản trị danh mục " + MyConst.DanhMuc.BaoCaoDinhKem.Ten;
            else if (MyMaDM == MyConst.DanhMuc.NoiDungMau1.Ma)
                lblFormName.InnerText = "Quản trị danh mục " + MyConst.DanhMuc.NoiDungMau1.Ten;
            else if (MyMaDM == MyConst.DanhMuc.NoiDungMau8.Ma)
                lblFormName.InnerText = "Quản trị danh mục " + MyConst.DanhMuc.NoiDungMau8.Ten;
            else if (MyMaDM == MyConst.DanhMuc.KyBaoCao.Ma)
                lblFormName.InnerText = "Quản trị danh mục " + MyConst.DanhMuc.KyBaoCao.Ten;
        }

        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            Response.Redirect("Index.aspx");
        }


        protected void grdDanhMuc_RowCommand(object sender, GridViewCommandEventArgs e)
        {

            ID = Convert.ToInt32(e.CommandArgument);


            if (e.CommandName == MyConst.Action.Update)
            {
                BindDataToDropDownNhomUser();
                BindDataToDropDownDonVi();
                formUpdate.Visible = true;
                PasswordField.Visible = false;
                txtUserName.Enabled = false;
                DataTable DanhMucTable = GetChiTietUser(ID);
                cboNhomUser.SelectedValue = DanhMucTable.Rows[0][1].ToString();
                txtUserName.Text = DanhMucTable.Rows[0][2].ToString();
                txtHoTen.Text = DanhMucTable.Rows[0][4].ToString();
                txtThongTin.Text = DanhMucTable.Rows[0][5].ToString();
                cboDonVi.SelectedValue = DanhMucTable.Rows[0][6].ToString();
                btnLuu.CommandName = MyConst.Action.Update;
            }
            else if (e.CommandName == MyConst.Action.Delete)
            {
                string sql = "DELETE FROM dbo.tblUser WHERE ID = @ID";
                List<SqlParameter> lstParameter = new List<SqlParameter>();
                lstParameter.Add(SqlHelper.CreateParameterObject("@ID", SqlDbType.Int, ParameterDirection.Input, ID));
                SqlHelper.ExecuteNonQuery(CommandType.Text, sql, lstParameter);
                BindDataToGrid("");
                MyCommon.AddMessage(this.Page.Master, "Xóa người dùng thành công", MyConst.MessageType.Success);
            }
        }

        protected void btnThem_Click(object sender, EventArgs e)
        {
            formUpdate.Visible = true;
            BindDataToDropDownNhomUser();
            BindDataToDropDownDonVi();
            txtHoTen.Text = MyMaDM;
            txtUserName.Text = "";
            txtUserName.Enabled = true;
            txtPassword.Text = "";
            txtRePassword.Text = "";
            PasswordField.Visible = true;
            RePasswordField.Visible = true;
            btnLuu.CommandName = MyConst.Action.Addnew;
        }

        protected void btnLuu_Click(object sender, EventArgs e)
        {
            int UserID = Convert.ToInt32(Session["userid"]);
            if (btnLuu.CommandName == MyConst.Action.Addnew)
            {
                InsertDanhMuc(
                    Convert.ToInt32(cboNhomUser.SelectedValue), 
                    txtUserName.Text, 
                    txtPassword.Text,
                    txtHoTen.Text,
                    txtThongTin.Text,
                    Convert.ToInt32(cboDonVi.SelectedValue),
                    UserID
                    );
                BindDataToGrid("");
                MyCommon.AddMessage(this.Page.Master, "Thêm người dùng thành công", MyConst.MessageType.Success);
            }
            else if (btnLuu.CommandName == MyConst.Action.Update)
            {
                UpdateDanhMuc(
                    Convert.ToInt32(cboNhomUser.SelectedValue),
                    txtHoTen.Text,
                    txtThongTin.Text,
                    Convert.ToInt32(cboDonVi.SelectedValue),
                    UserID,
                    ID
                    );
                BindDataToGrid("");
                MyCommon.AddMessage(this.Page.Master, "Cập nhật thông tin người dùng thành công", MyConst.MessageType.Success);
            }
        }

        protected void btnHuy_Click(object sender, EventArgs e)
        {
            formUpdate.Visible = false;
        }
        #endregion Ham su kien

        #region Ham chuc nang

        protected void BindDataToGrid(string UserName)
        {
            List<SqlParameter> arrParams = new List<SqlParameter>();
            arrParams.Add(SqlHelper.CreateParameterObject("@UserName", SqlDbType.NVarChar, ParameterDirection.Input, UserName));
            string sql = "SELECT U.ID,DM.TenDM AS NhomUser,Username,HoTen,U.ThongTin,DV.TenDV,U.CreateDate,U.UpdateDate,'Administrator' AS UpdateUser " +
                         "FROM dbo.tblUser U INNER JOIN dbo.tblDanhMuc DM ON DM.ID = U.NhomUserID_DM INNER JOIN dbo.tblDonVi DV ON DV.ID = U.DonViID " +
                         "WHERE Username LIKE @UserName OR HoTen LIKE '%'+@UserName+'%' OR U.ThongTin LIKE '%'+@UserName+'%' OR @UserName = ''";
            grdDanhMuc.DataSource = SqlHelper.ExecuteDataTable(CommandType.Text, sql, arrParams);
            grdDanhMuc.DataBind();
        }

        protected void BindDataToDropDownNhomUser() {
            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, "SELECT * FROM dbo.tblDanhMuc WHERE MaDM = 'NhomNguoiDung'");
            cboNhomUser.DataSource = dt;
            cboNhomUser.DataTextField = "TenDM";
            cboNhomUser.DataValueField = "ID";
            cboNhomUser.DataBind();
            cboNhomUser.Items.Insert(0, new ListItem("Chọn nhóm người dùng", "-1"));
        }

        protected void BindDataToDropDownDonVi()
        {
            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, "SELECT * FROM dbo.tblDonVi");
            cboDonVi.DataSource = dt;
            cboDonVi.DataTextField = "TenDV";
            cboDonVi.DataValueField = "ID";
            cboDonVi.DataBind();
            cboDonVi.Items.Insert(0, new ListItem("Chọn đơn vị", "-1"));
        }

        protected DataTable GetChiTietUser(int ID)
        {
            List<SqlParameter> arrParams = new List<SqlParameter>();
            arrParams.Add(SqlHelper.CreateParameterObject("@ID", SqlDbType.Int, ParameterDirection.Input, ID));
            return SqlHelper.ExecuteDataTable(CommandType.Text, "SELECT * FROM dbo.tblUser WHERE ID = @ID", arrParams);
        }

        protected void InsertDanhMuc(int NhomUserID, string UserName, string Password, string HoTen, string ThongTin, int DonViID, int UserID)
        {
            List<SqlParameter> arrParams = new List<SqlParameter>();
            arrParams.Add(SqlHelper.CreateParameterObject("@NhomUserID_DM", SqlDbType.Int, ParameterDirection.Input, NhomUserID));
            arrParams.Add(SqlHelper.CreateParameterObject("@Username", SqlDbType.NVarChar, ParameterDirection.Input, UserName));
            Password = FormsAuthentication.HashPasswordForStoringInConfigFile(Password, "MD5");
            arrParams.Add(SqlHelper.CreateParameterObject("@Password", SqlDbType.NVarChar, ParameterDirection.Input, Password));
            arrParams.Add(SqlHelper.CreateParameterObject("@HoTen", SqlDbType.NVarChar, ParameterDirection.Input, HoTen));
            arrParams.Add(SqlHelper.CreateParameterObject("@ThongTin", SqlDbType.NVarChar, ParameterDirection.Input, ThongTin));
            arrParams.Add(SqlHelper.CreateParameterObject("@DonViID", SqlDbType.Int, ParameterDirection.Input, DonViID));
            arrParams.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.Int, ParameterDirection.Input, UserID));
            string sql = "INSERT INTO dbo.tblUser" +
                         "(NhomUserID_DM,Username,Password,HoTen,ThongTin,DonViID,IsAdmin,CreateDate,UpdateDate,UserID)" +
                         "VALUES(@NhomUserID_DM,@Username,@Password,@HoTen,@ThongTin,@DonViID,0,GETDATE(),GETDATE(),@UserID)";
            SqlHelper.ExecuteNonQuery(CommandType.Text, sql, arrParams);
        }

        protected void UpdateDanhMuc(int NhomUserID, string HoTen, string ThongTin, int DonViID, int UserID, int ID)
        {
            List<SqlParameter> arrParams = new List<SqlParameter>();
            arrParams.Add(SqlHelper.CreateParameterObject("@NhomUserID", SqlDbType.Int, ParameterDirection.Input, NhomUserID));
            arrParams.Add(SqlHelper.CreateParameterObject("@HoTen", SqlDbType.NVarChar, ParameterDirection.Input, HoTen));
            arrParams.Add(SqlHelper.CreateParameterObject("@ThongTin", SqlDbType.NVarChar, ParameterDirection.Input, ThongTin));
            arrParams.Add(SqlHelper.CreateParameterObject("@DonViID", SqlDbType.Int, ParameterDirection.Input, DonViID));
            arrParams.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.Int, ParameterDirection.Input, UserID));
            arrParams.Add(SqlHelper.CreateParameterObject("@ID", SqlDbType.Int, ParameterDirection.Input, ID));
            string sql = "UPDATE dbo.tblUser SET NhomUserID_DM = @NhomUserID,HoTen = @HoTen,ThongTin = @ThongTin,DonViID = @DonViID,UserID = @UserID WHERE ID = @ID";
            SqlHelper.ExecuteNonQuery(CommandType.Text, sql, arrParams);
        }

        public bool CheckPermision()
        {
            if (Session["username"] == null)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        #endregion  Ham chuc nang

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindDataToGrid(txtSearch.Text.Trim());
        }
    }
}